package com.eascs.admin.o2o.specialInterview.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.internal.util.BaseUserUtil;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.specialInterview.entity.O2OSpecialInterview;
import com.eascs.admin.o2o.specialInterview.form.O2OSpecialInterviewForm;
import com.eascs.admin.o2o.specialInterview.service.O2OSpecialInterviewService;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;

/**
 * 面签申报提交
 * 
 * @author yy
 *
 */
@RestController
@RequestMapping("/rspecialInterview")
public class O2OSpecialInterviewSubmitController extends BaseRestController {
	private static Logger logger = LoggerFactory.getLogger(O2OSpecialInterviewSubmitController.class);
	@Autowired
	O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	BaseUserUtil userUtils;
	@Reference
	private WorkFlowService workFlowService;
	@Reference
	ICustomerInfoService iCustomerInfoService;
	
	@Autowired
	O2OSpecialInterviewService o2OSpecialInterviewService;
	
	/**
	 * 保存特殊面签申报数据。
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/save_form")
	public BaseRestResult<String> approval(O2OSpecialInterviewForm specialInterviewForm) {
		O2oLoanapplyEntity entity = o2oLoanapplyService.findById(specialInterviewForm.getLoanapplyNo());
		if (StringUtil.isEmpty(specialInterviewForm.getLoanapplyNo())) {
			return BaseRestResult.warn("贷款单号不能为空");
		}
		//是否已经存在特殊申报流程
		O2OSpecialInterview o2OSpecialInterview = o2OSpecialInterviewService.queryEntity(specialInterviewForm.getLoanapplyNo());
		 if(o2OSpecialInterview==null){
			 O2OSpecialInterview o2OSpecialInterviewAdd = new O2OSpecialInterview();
			 o2OSpecialInterviewAdd.setBillCode(entity.getBillCode());
			 o2OSpecialInterviewAdd.setLoanapplyNo( entity.getLoanapplyNo());
			 o2OSpecialInterviewAdd.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);
			 o2OSpecialInterviewAdd.setCreatorId(userUtils.getCreateOr());
			 o2OSpecialInterviewAdd.setCreatTime(userUtils.getCreateTime());
			 o2OSpecialInterviewAdd.setCreatorName(userUtils.getUserName());
			 o2OSpecialInterviewAdd.setIslock(StatusContexts.O2O_NO);
			 o2OSpecialInterviewService.save(o2OSpecialInterviewAdd);
		 }
		
		 BaseRestResult<String> reslut = startUp(entity.getLoanapplyNo());
		 if(reslut.getAction().equals(BaseRestResult.ACTION_INFO)){
			 return BaseRestResult.info(reslut.getMessage()).andRefresh();
		 }else{
			 return BaseRestResult.warn(reslut.getMessage());
		 }
		
		 //return BaseRestResult.info("操作成功").andRedirect(UrlHelper.build("/backfee/list"));
	}
	
	@RequestMapping(value = "/startup")
	public BaseRestResult<String> startUp(String referId) {
		 O2OSpecialInterview o2OSpecialInterviewStart = o2OSpecialInterviewService.queryEntity(referId);
		O2oLoanapplyEntity apply = null;
		apply = o2oLoanapplyService.fingByBillCode(o2OSpecialInterviewStart.getBillCode());
		// 存库成功 启动退费流程
		ModelResult<Boolean> modelResult = startMQSB(apply);
		// 流程启动后更新主表
		logger.info("start-up Technological process result params isSuccess:{},ErrCode:{},ErrMsg:{},etailStack:{}", modelResult.isSuccess(), modelResult.getErrCode(), modelResult.getErrMsg(), modelResult.getDetailStack());
		if (modelResult.isSuccess()) {
			o2OSpecialInterviewService.updateWorkFlowStatus(StatusContexts.WFTYPE_STATUS_RUN, apply.getLoanapplyNo());
			// 流程启动后更新主表
			//return BaseRestResult.info("操作成功").andRedirect(UrlHelper.build("/backfee/list"));
			return BaseRestResult.info("操作成功");
		}
		
		return BaseRestResult.warn(modelResult.getErrMsg());
	}
	/**
	 * 启动特殊面签流程
	 */
	public ModelResult<Boolean> startMQSB(O2oLoanapplyEntity loan) { // 根据单号去启动流程
		logger.info("贷款编号：[{}],贷款类型：[{}],启动特殊面签流程", loan.getBillCode(),loan.getLoanType());
		//TODO
		WFRequestParam param = new WFRequestParam();
		param.setReferId(loan.getLoanapplyNo());
		param.setReferCode(loan.getBillCode());
		param.setReferUrl("http://xxxx.eascs.com/getDetail");
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_SPEC_BANK_REPORT));
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(loan.getLtd());

		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(),loan.getLoanId()).getUserFullName());
		appliedDes.append("，申请金额:");
		java.text.DecimalFormat df=new java.text.DecimalFormat("0.00"); //格式化，保留两位小数
		appliedDes.append(df.format(loan.getLoanaMount().doubleValue()));
		param.setAppliedDes(appliedDes.toString());
		logger.info("启动特殊面签流程WFRequestParam对象：[{}]", param.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		return modelResult;
	}
	
}
